import { QueryClient, useQuery } from 'react-query';
import { dehydrate } from 'react-query/hydration'
import { useRouter } from "next/router";
import CourseLayout from "@/components/course-layout";
import CourseChapterList from "@/components/course-chapter-list";
import { getCourseById } from "@/apis/course";
import { getChapters } from "@/apis/chapter";
import { isCourseManager } from '@/tools/data-helpers';

export default function ChapterHomePage() {
    const { courseId } = useRouter().query;

    const { data: course } = useQuery(['course', courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getCourseById(courseId)
    });

    const { data: chapters } = useQuery(['chapters', courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getChapters(courseId);
    });

    return (
        <CourseLayout courseId={courseId} course={course}>
            <CourseChapterList courseId={courseId} chapters={chapters} isCourseManager={isCourseManager(course && course.manager)} />
        </CourseLayout>
    );
}

export async function getServerSideProps({ query }) {
    const queryClient = new QueryClient()

    await queryClient.prefetchQuery(['course', query.courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getCourseById(courseId);
    });
    await queryClient.prefetchQuery(['chapters', query.courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getChapters(courseId);
    });

    return {
        props: {
            dehydratedState: dehydrate(queryClient),
        },
    }
}
